package cn.jiyun.order.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.IdUtil;
import cn.jiyun.common.vo.CommonResult;
import cn.jiyun.model.*;
import cn.jiyun.model.dto.OrderDto;
import cn.jiyun.order.feign.AddressFeign;
import cn.jiyun.order.feign.CouponFeign;
import cn.jiyun.order.mapper.OrderItemMapper;
import cn.jiyun.order.mapper.OrderMapper;
import cn.jiyun.order.service.OrderService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.commons.util.IdUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
@Autowired
private  OrderMapper orderMapper;
@Autowired
private RedisTemplate<String,String> redisTemplate;
@Autowired
private AddressFeign addressFeign;
@Autowired
private CouponFeign couponFeign;
@Autowired
private OrderItemMapper orderItemMapper;

    @Override
    public CommonResult submitYourOrder(OrderDto orderDto) {

            Integer addressId = orderDto.getAddressId();
            Address addresses = addressFeign.addressByid(addressId);
            Integer couponId = orderDto.getCouponId();
            RecordingCoupon recordingCoupon=couponFeign.RecordingCouponfindByid(couponId);
            if (addresses==null){
                return  CommonResult.error("没有该地址");
            }
            if (recordingCoupon==null){
                return  CommonResult.error("没有该优惠卷");
            }
            String redisCart = (String) redisTemplate.boundHashOps("shoppingCart").get(orderDto.getUserId() + "");
            if (redisCart==null){
                return  CommonResult.error("redis中没有的数据");
            }
            List<ShoppingCart> shoppingCarts = JSON.parseArray(redisCart, ShoppingCart.class);
            int sum=0;
            for (ShoppingCart shoppingCart : shoppingCarts) {
                sum=sum+shoppingCart.getSpecsPrice().intValue();
            }
            System.out.println(sum);
            if ( !(sum == orderDto.getBasePrice().intValue())){
                return  CommonResult.error("购买的价格不对");
            }
            Coupon coupon =couponFeign.CouponfindByid(recordingCoupon.getCouponId());
            System.out.println(sum-coupon.getCouponValue());
            if (!(orderDto.getTotal().intValue()==sum-coupon.getCouponValue())){
                return  CommonResult.error("总计价格不对");
            }
            Order order = new Order();
            order.setOrderId(String.valueOf(IdUtil.getSnowflake(1,1).nextId()));
            order.setUserId(orderDto.getUserId());
            order.setAddressDetailed(addresses.getDetailed());
            order.setAddressName(addresses.getName());
            order.setAddressPhone(addresses.getPhone());
            order.setCouponId(orderDto.getCouponId());
            order.setStatus(1);
            order.setTotal(orderDto.getTotal());
            order.setBasePrice(orderDto.getBasePrice());
            order.setAddressRegion(addresses.getRegion());
            order.setUnderTime(LocalDateTime.now());
            orderMapper.insert(order);
            for (ShoppingCart shoppingCart : shoppingCarts) {
                OrderItem orderItem = new OrderItem();
                orderItem.setBaseId(shoppingCart.getBaseId());
                orderItem.setBasePrice(shoppingCart.getSpecsPrice());
                orderItem.setNum(shoppingCart.getBaseNum());
                orderItem.setOrderId(order.getId());
                orderItemMapper.insert(orderItem);
            }
            Integer id = recordingCoupon.getId();
            couponFeign.RecordingCouponUpdate(id);

//        redisTemplate.boundHashOps("shoppingCart").delete(orderDto.getUserId()+"");
            return CommonResult.success("提交成功",order);

        }


    @Override
    public String tokenFindAll() {
        String token = IdUtil.getSnowflake().nextIdStr();
        redisTemplate.opsForValue().set("token:"+token,123456+"");
        return token;
    }

    @Override
    public boolean validToken(String token,String value) {
        String script = "if redis.call('get',KEYS[1])==KEYS[2] then return redis.call('del',KEYS[1]) else return 0 end";
        RedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
        Long result = redisTemplate.execute(redisScript, Arrays.asList("token:" + token, value));
        if (result!=null&&result!=0L){
            log.info("验证token={},key={},value={}成功",token,"token:"+token,value);
            return true;
        }else{
            log.info("验证token={},key={},value={}失败",token,"token:"+token,value);
            return false;
        }

    }

    @Override
    public CommonResult paymentFeatures(Integer userId) {
        LambdaQueryWrapper<Order> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderLambdaQueryWrapper.eq(Order::getUserId,userId);
        Order order = orderMapper.selectOne(orderLambdaQueryWrapper);
        order.setPayTime(LocalDateTime.now());
        order.setPayId(IdUtil.getSnowflake().nextIdStr());
        orderMapper.updateById(order);
        return CommonResult.success("支付成功");
    }


}
